package com.zone.vehicle.superapp.view.login.setSecret;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.account.entity.CaptchaGetEntity;
import com.zone.sdk.module.account.entity.CheckCaptchaEntity;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.vehicle.lib.view.captcha.model.CaptchaGetIt;
import com.zone.vehicle.lib.view.captcha.widget.BlockPuzzleDialog;
import com.zone.vehicle.lib.view.captcha.widget.DragImageView;
import com.zone.vehicle.superapp.databinding.FragmentResetSecretBinding;
import com.zone.vehicle.superapp.model.LoginViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.PhoneUtils;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.atomic.AtomicBoolean;

import static com.zone.vehicle.superapp.view.login.setSecret.ForgetSecretFragment.SET_CODE_FRAGMENT;

public class ResetSecretFragment extends BaseFragment {

    private FragmentResetSecretBinding binding;
    private BlockPuzzleDialog blockPuzzleDialog;
    private LoginViewModel viewModel;
    private AtomicBoolean mObserving = new AtomicBoolean(false);
    private Observer<CheckCaptchaEntity> mCheckCaptchaObserver = new Observer<CheckCaptchaEntity>() {
        @Override
        public void onChanged(CheckCaptchaEntity checkCaptchaEntity) {
            if (!mObserving.get()) {
                return;
            }
            if (ObjectUtils.isEmpty(checkCaptchaEntity)) {
                blockPuzzleDialog.resetCheck();
                viewModel.captchaGet();
            }
        }
    };

    private Observer<CaptchaGetEntity> mCaptchaGetItObserver = new Observer<CaptchaGetEntity>() {
        @Override
        public void onChanged(CaptchaGetEntity captchaGetEntity) {
            if (!mObserving.get()) {
                return;
            }
            if (ObjectUtils.isNotEmpty(captchaGetEntity)) {
                binding.loading.setVisibility(View.GONE);
                CaptchaGetIt data = new CaptchaGetIt();
                data.setJigsawImageBase64(captchaGetEntity.getJigsawImageBase64());
                data.setOriginalImageBase64(captchaGetEntity.getOriginalImageBase64());
                data.setSecretKey(captchaGetEntity.getSecretKey());
                data.setToken(captchaGetEntity.getToken());
                blockPuzzleDialog.setData(data);
                blockPuzzleDialog.show();
            }
        }
    };

    public ResetSecretFragment() {

    }

    public String getPhone() {
        return binding.phone.getText().toString();
    }

    public String getCaptchaCertificate() {
        return viewModel.getCaptcha_certificate().getValue();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentResetSecretBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this, new ViewModelFactory()).get(LoginViewModel.class);
        init();
        return binding.getRoot();
    }

    private void init() {
        blockPuzzleDialog = new BlockPuzzleDialog(this.requireContext());

        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });

        binding.btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PhoneUtils.isPhoneNum(binding.phone.getText().toString())) {
                    Toast.makeText(
                            requireContext(),
                            "请输入手机号码",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                viewModel.captchaGet();
            }
        });
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultMsg());
                }
            }
        });
        blockPuzzleDialog.setDragListener(new DragImageView.DragListenner() {
            @Override
            public void onDrag(double position) {
                CaptchaGetEntity entity = viewModel.getCaptchaGet().getValue();
                if (ObjectUtils.isNotEmpty(entity)) {
                    viewModel.checkCaptcha(position, entity.getToken(), entity.getSecretKey());
                }
            }
        });

        viewModel.getCaptcha_certificate().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isNotEmpty(s)) {
                    blockPuzzleDialog.ok();
                    blockPuzzleDialog.cancel();
                    viewModel.loginPhoneCode(requireContext(), binding.phone.getText().toString(), s);
                }
            }
        });
        viewModel.getLoginEntity().observe(getViewLifecycleOwner(), new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (ObjectUtils.isNotEmpty(loginEntity)) {
                    changePage(SET_CODE_FRAGMENT);
                }
            }
        });
    }

    private void startObserve() {
        viewModel.getCheckCaptcha().observe(getViewLifecycleOwner(), mCheckCaptchaObserver);
        viewModel.getCaptchaGet().observe(getViewLifecycleOwner(), mCaptchaGetItObserver);
        mObserving.set(true);
    }

    private void stopObserve() {
        mObserving.set(false);
        viewModel.getCheckCaptcha().removeObserver(mCheckCaptchaObserver);
        viewModel.getCaptchaGet().removeObserver(mCaptchaGetItObserver);
    }

    @Override
    public void onResume() {
        super.onResume();
        startObserve();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopObserve();
        clean();
    }

    private void clean() {
        binding.phone.setText("");
        viewModel.getError().setValue(null);
        viewModel.getCaptchaGet().setValue(null);
        viewModel.getCheckCaptcha().setValue(null);
        viewModel.getLoginEntity().setValue(null);
        viewModel.getCaptcha_certificate().setValue(null);
    }
}